package com.wfcm.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.wfcm.dao.WfGoodsOrderDao;
import com.wfcm.entity.WfGoodsOrderEntity;
import com.wfcm.service.WfGoodsOrderService;
import com.wfcm.utils.ConstantUtil;
import com.wfcm.wxPay.WXPrepay;
import com.wfcm.wxPay.WXPay;



@Service("wfGoodsOrderService")
public class WfGoodsOrderServiceImpl implements WfGoodsOrderService {
	private Logger log = Logger.getLogger(Properties.class) ;  
	@Autowired
	private WfGoodsOrderDao wfGoodsOrderDao;
	
	@Override
	public WfGoodsOrderEntity queryObject(Integer id){
		return wfGoodsOrderDao.queryObject(id);
	}
	
	@Override
	public List<WfGoodsOrderEntity>  queryByUserId(Integer uid){
		return wfGoodsOrderDao.queryByUserId(uid);
	}

	@Override
	public WfGoodsOrderEntity queryByCollageId(Map<String, Object> map){
		return wfGoodsOrderDao.queryByCollageId(map);
	}

	@Override
	public List<WfGoodsOrderEntity> queryList(Map<String, Object> map){
		return wfGoodsOrderDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return wfGoodsOrderDao.queryTotal(map);
	}
	//获取待付款个数
	@Override
	public int queryNoPay(Map<String, Object> map){
		return wfGoodsOrderDao.queryNoPay(map);
	}
	//获取已付款个数
	@Override
	public int queryAlreadyPay(Map<String, Object> map){
		return wfGoodsOrderDao.queryAlreadyPay(map);
	}
	
	@Override
	public void save(WfGoodsOrderEntity wfGoodsOrder){
		wfGoodsOrderDao.save(wfGoodsOrder);
	}
	
	@Override
	public void update(WfGoodsOrderEntity wfGoodsOrder){
		wfGoodsOrderDao.update(wfGoodsOrder);
	}
	
	@Override
	public void delete(Integer id){
		wfGoodsOrderDao.delete(id);
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		wfGoodsOrderDao.deleteBatch(ids);
	}

	@Override
	public List<WfGoodsOrderEntity> queryMyOrder(Map<String, Object> map) {
		
		return wfGoodsOrderDao.queryMyOrder(map);
	}

	@Override
	public JSONObject dopay(HttpServletRequest request, String orderNum, BigDecimal actualPrice,
            Integer orderType) throws Exception {
		JSONObject res = new JSONObject();
		res.put("errCode", 0);
		//通知的URL
		//String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()  + request.getContextPath() + "/";
		String basePath = "";
		if("product".equals(ConstantUtil.environment)){
			basePath = "http://wfnx.wfkids.net/wfcm-api/";
		}else{
			basePath = "https://wftest.wfkids.net/wfcm-api/";
		}
		String notifyUrl = basePath + "order/wechatreceive";
		String prepayid = getWXPrePayId(request, orderNum, actualPrice, orderType, notifyUrl);
		if (prepayid != null && prepayid.length() > 10) {
		    // 生成微信支付参数，此处拼接为完整的JSON格式，符合支付调起传入格式
		    String jsParam = WXPay.createPackageValue(ConstantUtil.APP_ID, ConstantUtil.PARTNER_KEY, prepayid);
		    log.info("生成的微信调起参数为：" + jsParam);
		    // 此处可以添加订单的处理逻辑
		    JSONObject params = JSONObject.parseObject(jsParam);
		    res.putAll(params);
		}
		return res;
	}
	
	@Override
	public JSONObject ggdopay(HttpServletRequest request, String orderNum, BigDecimal actualPrice,
            Integer orderType,String openid) throws Exception {
		JSONObject res = new JSONObject();
		res.put("errCode", 0);
		//通知的URL
		//String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()  + request.getContextPath() + "/";
		String basePath = "";
		if("product".equals(ConstantUtil.environment)){
			basePath = "http://wfnx.wfkids.net/wfcm-api/";
		}else{
			basePath = "https://wftest.wfkids.net/wfcm-api/";
		}
		String notifyUrl = basePath + "order/wechatreceive";
		String prepayid = getGgWXPrePayId(request, orderNum, actualPrice, orderType, notifyUrl,openid);
		if (prepayid != null && prepayid.length() > 10) {
		    // 生成微信支付参数，此处拼接为完整的JSON格式，符合支付调起传入格式
		    String jsParam = WXPay.createPublicPackageValue(ConstantUtil.GG_APP_ID, ConstantUtil.GG_PARTNER_KEY,prepayid);
		    log.info("生成的微信调起参数为：" + jsParam);
		    // 此处可以添加订单的处理逻辑
		    JSONObject params = JSONObject.parseObject(jsParam);
		    res.putAll(params);
		}
		return res;
	}
	
	@Override
	public JSONObject doQuery(HttpServletRequest request, String orderNum, BigDecimal actualPrice,
            Integer orderType) throws Exception {
		JSONObject res = new JSONObject();
		res.put("errCode", 0);
		//通知的URL
		//String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()  + request.getContextPath() + "/";
		String basePath = "";
		if("product".equals(ConstantUtil.environment)){
			basePath = "http://wfnx.wfkids.net/wfcm-api/";
		}else{
			basePath = "https://wftest.wfkids.net/wfcm-api/";
		}
		String notifyUrl = basePath + "order/wechatreceive";
		String prepayid = getWXPrePayId(request, orderNum, actualPrice, orderType, notifyUrl);
		if (prepayid != null && prepayid.length() > 10) {
		    // 生成微信支付参数，此处拼接为完整的JSON格式，符合支付调起传入格式
		    String jsParam = WXPay.createPackageValue(ConstantUtil.APP_ID, ConstantUtil.PARTNER_KEY, prepayid);
		    log.info("生成的微信调起参数为：" + jsParam);
		    // 此处可以添加订单的处理逻辑
		    JSONObject params = JSONObject.parseObject(jsParam);
		    res.putAll(params);
		}
				
		return res;
	}
	
	/**
     * 创建微信prepayid
     * 
     * @param notifyUrl
     * @return
     */
    private String getWXPrePayId(HttpServletRequest request, String orderCode, BigDecimal actualPrice,
            Integer orderType, String notifyUrl) {
        String payMoney = String.valueOf(actualPrice.multiply(new BigDecimal(100)).intValue());
        String item ="好芳法课堂-APP";
		if("test".equals(ConstantUtil.environment)){// 写死0.01元
			payMoney = "1";//单位为分
		}
        String remoteIPAddress = request.getRemoteAddr();
         //remoteIPAddress="123.57.80.58";
        // 商户相关资料
        String appid = ConstantUtil.APP_ID;
        // String appsecret = ConstantUtil.APP_SECRET;
        String partner = ConstantUtil.PARTNER;
        String partnerkey = ConstantUtil.PARTNER_KEY;

        WXPrepay prePay = new WXPrepay();
        prePay.setAppid(appid);
        prePay.setBody(item);
        prePay.setPartnerKey(partnerkey);
        prePay.setMch_id(partner);
        prePay.setNotify_url(notifyUrl);
        prePay.setOut_trade_no(orderCode);
        prePay.setSpbill_create_ip(remoteIPAddress);
        prePay.setTotal_fee(payMoney);
        prePay.setTrade_type("APP");

        String prepayid = prePay.submitXmlGetPrepayId();
        log.info("获取的预支付订单是：" + prepayid);
        return prepayid;
    }

    /**
     * 创建微信prepayid
     * @param notifyUrl
     * @return
     */
    @SuppressWarnings("unused")
	private String getGgWXPrePayId(HttpServletRequest request, String orderCode, BigDecimal actualPrice,
            Integer orderType, String notifyUrl,String openid) {
        String payMoney = String.valueOf(actualPrice.multiply(new BigDecimal(100)).intValue());
        String item ="好芳法课堂-公众号购课";
		if("test".equals(ConstantUtil.environment)){// 写死0.01元
			payMoney = "1";//单位为分
		}
        String remoteIPAddress = request.getRemoteAddr();
        //remoteIPAddress="123.57.80.58";
        // 商户相关资料
        String appid = ConstantUtil.GG_APP_ID;
        //String appsecret = ConstantUtil.APP_SECRET;
        String partner = ConstantUtil.GG_PARTNER;
        String partnerkey = ConstantUtil.GG_PARTNER_KEY;

        WXPrepay prePay = new WXPrepay();
        prePay.setAppid(appid);
        prePay.setBody(item);
        prePay.setPartnerKey(partnerkey);
        prePay.setMch_id(partner);
        prePay.setNotify_url(notifyUrl);
        prePay.setOut_trade_no(orderCode);
        prePay.setSpbill_create_ip(remoteIPAddress);
        prePay.setTotal_fee(payMoney);
        prePay.setTrade_type("JSAPI");
        prePay.setOpenid(openid);

        String prepayid = prePay.submitGgXmlGetPrepayId();
        log.info("获取的预支付订单是：" + prepayid);
        return prepayid;
    }

    
	@Override
	public WfGoodsOrderEntity queryByOrderCode(String orderCode) {
		// TODO Auto-generated method stub
		return wfGoodsOrderDao.queryByOrderCode(orderCode);
	}
	
	@Override
	public WfGoodsOrderEntity queryByTransactionId(String transactionId) {
		// TODO Auto-generated method stub
		return wfGoodsOrderDao.queryByTransactionId(transactionId);
	}

	@Override
	public WfGoodsOrderEntity queryOrderUser(String orderCode) {
		// TODO Auto-generated method stub
		return wfGoodsOrderDao.queryOrderUser(orderCode);
	}

	@Override
	public Integer queryAlreadyPayByUserId(Integer userId) {
		return wfGoodsOrderDao.queryAlreadyPayByUserId(userId);
	}


}
